<template>
  <v-container>
    <v-card class="mt-4">
      <v-card-title>
        <span class="headline">句型可视化分析</span>
      </v-card-title>
      <v-card-subtitle>句型统计</v-card-subtitle>

      <!-- 语法结构分析：饼状图 -->
      <v-row>
        <v-col cols="6">
          <v-card class="pa-4">
            <div ref="syntaxChart" style="width: 100%; height: 400px;"></div>
          </v-card>
        </v-col>

        <!-- 亮点句子展示 -->
        <v-col cols="6">
          <v-card class="pa-4">
            <v-list dense>
              <v-list-item-group v-if="highlightSentences.length > 0">
                <v-list-item
                    v-for="(sentence, index) in highlightSentences"
                    :key="index"
                    @click="showSyntaxTree(sentence)">
                  <v-list-item-content>
                    <v-list-item-title>{{ sentence }}</v-list-item-title>
                  </v-list-item-content>
                </v-list-item>
              </v-list-item-group>
              <v-list-item v-else>
                <v-list-item-content>
                  <v-list-item-title>暂无亮点句子</v-list-item-title>
                </v-list-item-content>
              </v-list-item>
            </v-list>
          </v-card>
        </v-col>
      </v-row>
    </v-card>

    <!-- 亮点句子拆解对话框 -->
    <v-dialog v-model="dialogVisible" max-width="800px">
      <v-card>
        <v-card-title class="headline justify-center">亮点句子拆解</v-card-title>
        <v-card-text>
          <div v-if="sentenceDetails.sentence">
            <p><strong>原句：</strong> {{ sentenceDetails.sentence }}</p>
            <p><strong>句型类型：</strong> {{ sentenceDetails.type }}</p>
            <div class="d-flex mb-4">
              <p><strong>语法结构：</strong></p>
              <div ref="syntaxStructure" class="displacy-container" style="width: 100%; max-height: 200px; overflow-x: auto;"></div>
            </div>
            <p><strong>句法层次关系树：</strong></p>
            <div class="d-flex">
            <div ref="syntaxTree" style="width: 600px; height: 400px;"></div>
            </div>
            <p><strong>优化建议：</strong> {{ sentenceDetails.suggestion }}</p>
          </div>
          <div v-else>
            <p>暂无数据</p>
          </div>
        </v-card-text>
        <v-card-actions>
          <v-btn color="blue" text @click="dialogVisible = false">关闭</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

  </v-container>
</template>

<script>
import * as echarts from "echarts";
import { analyzeSyntax, fetchSyntaxTree, fetchSyntaxStructure } from "@/api/essay";
import {mapGetters} from "vuex";

export default {
  name: "PersonalizedReport",
  data() {
    return {
      highlightSentences: [],
      dialogVisible: false,
      treeData: null,
      sentenceDetails: {
        sentence: "",
        type: "",
        structure: null,
        suggestion: "",
      }
    };
  },
  computed: {
    ...mapGetters(['userEssay']),
  },
  watch: {
    userEssay(newEssay) {
      console.log("监听到 userEssay 更新:", newEssay);

      if (newEssay && newEssay.trim()) {
        console.log("触发 analyzeEssay 方法");
        this.analyzeEssay(newEssay);
      } else {
        console.warn("作文数据为空，清空分析结果");
        this.clearAnalysisData();
      }
    }
  },
  mounted() {
    console.log("PersonalizedReport 组件挂载，当前 userEssay：", this.userEssay);

    if (!this.userEssay || !this.userEssay.trim()) {
      console.log("页面刷新，清空数据");
      this.clearAnalysisData();
    } else {
      console.log("执行 analyzeEssay 方法");
      this.analyzeEssay(this.userEssay);
    }
  },

  methods: {
    /**
     * 1. 分析整篇作文，生成句型统计图表并提取亮点句子
     */
    async analyzeEssay(essay) {
      try {
        const response = await analyzeSyntax(essay);
        console.log("分析结果:", response.data);

        const { syntaxData, highlightSentences } = response.data.result;

        this.highlightSentences = highlightSentences || [];
        this.$nextTick(() => {
          this.generateSyntaxChart(syntaxData.data || []);
        });

      } catch (error) {
        console.error("获取句法分析失败:", error);
        this.highlightSentences = [];
      }
    },
    /**
     * 2. 生成句型统计饼图
     */
    generateSyntaxChart(data) {
      const chartElement = this.$refs.syntaxChart;
      if (!chartElement) {
        console.warn("未找到 syntaxChart 容器");
        return;
      }

      const chart = echarts.init(chartElement);
      const sentenceTypes = ["简单句", "复合句", "复杂句", "复合-复杂句"];

      if (!Array.isArray(data) || data.length === 0) {
        console.warn("数据为空或格式不正确:", data);
        chart.clear();
        return;
      }

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        series: [
          {
            name: '句型统计',
            type: 'pie',
            radius: '55%',
            data: data.map((value, index) => ({
              value,
              name: sentenceTypes[index] || `句型 ${index + 1}`,
            })),
          },
        ],
      };

      chart.setOption(option);
    },

    // 3. 语法结构渲染 (Displacy 格式)
    async renderSyntaxStructure(sentence) {
      try {
        const response = await fetchSyntaxStructure(sentence);
        const data = response.data;

        if (!data || !data.html) {
          console.warn("语法结构数据为空或格式不正确：", data);
          return;
        }

        const container = this.$refs.syntaxStructure;

        if (!container) {
          console.warn("语法结构容器未找到");
          return;
        }

        // ✅ 清空之前内容，防止叠加
        container.innerHTML = '';

        // ✅ 插入新内容
        container.innerHTML = data.html;

        // ✅ 确保 SVG 加载完成后再执行样式调整和缩放功能
        this.observeSVGLoad(container);

      } catch (error) {
        console.error("获取语法结构失败:", error);
      }
    },

    /**
     * 监听 SVG 元素的加载完成
     */
    observeSVGLoad(container) {
      const observer = new MutationObserver(() => {
        const svg = container.querySelector("svg");

        if (svg) {
          // ✅ 调整 SVG 样式
          this.adjustDisplacyStyles(svg);

          // ✅ 启用缩放功能
          this.enableSVGZoom(svg);

          // ✅ 断开监听，避免重复执行
          observer.disconnect();
        }
      });

      observer.observe(container, { childList: true, subtree: true });
    },
    /**
     * 调整 SVG 样式
     */
    adjustDisplacyStyles(svg) {
      if (!svg) return;

      // ✅ 调整 SVG 尺寸及布局
      svg.style.width = "100%";
      svg.style.height = "100%";
      svg.style.maxWidth = "100%";
      svg.style.overflow = "visible";

      const bbox = svg.getBBox();
      const width = bbox.width > 0 ? bbox.width : 600;
      const height = bbox.height > 0 ? bbox.height : 200;

      svg.setAttribute("viewBox", `0 0 ${width} ${height}`);

      // ✅ 背景透明化
      svg.querySelectorAll(".bg").forEach((bg) => {
        bg.setAttribute("fill", "none");
        bg.setAttribute("stroke", "none");
      });

      // ✅ 修改词汇节点样式
      svg.querySelectorAll(".word").forEach((word) => {
        word.style.fontSize = "12px";
        word.style.fontWeight = "500";
        word.style.fill = "#333";
      });

      // ✅ 修改依存关系标签样式
      svg.querySelectorAll(".dep").forEach((dep) => {
        dep.style.fontSize = "10px";
        dep.style.fill = "#666";
      });

      // ✅ 修改箭头样式，仅显示轮廓，无填充
      svg.querySelectorAll(".arrow path").forEach((arrow) => {
        arrow.setAttribute("stroke", "#4A90E2");
        arrow.setAttribute("stroke-width", "1.2");
        arrow.setAttribute("fill", "none");
      });

      // ✅ 修改箭头文字样式
      svg.querySelectorAll(".arrow text").forEach((text) => {
        text.style.fontSize = "10px";
        text.style.fill = "#888";
      });
    },
    //SVG缩放功能
    enableSVGZoom(svg) {
      let scale = 1;
      const MIN_SCALE = 0.5;
      const MAX_SCALE = 10;

      // ✅ 初始偏移量
      let offsetX = 0;
      let offsetY = 0;

      // ✅ 拖拽相关变量
      let startX = 0, startY = 0;
      let isDragging = false;

      // ✅ 鼠标滚轮缩放
      svg.addEventListener("wheel", (e) => {
        e.preventDefault();
        const delta = e.deltaY > 0 ? -0.1 : 0.1;
        scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, scale + delta));

        // ✅ 应用缩放和偏移量
        svg.style.transform = `translate(${offsetX}px, ${offsetY}px) scale(${scale})`;
      });

      // ✅ 拖拽开始
      svg.addEventListener("mousedown", (e) => {
        isDragging = true;
        startX = e.clientX - offsetX;
        startY = e.clientY - offsetY;
        svg.style.cursor = "grabbing";
      });

      // ✅ 拖拽进行
      window.addEventListener("mousemove", (e) => {
        if (!isDragging) return;

        offsetX = e.clientX - startX;
        offsetY = e.clientY - startY;

        // ✅ 应用缩放和偏移量
        svg.style.transform = `translate(${offsetX}px, ${offsetY}px) scale(${scale})`;
      });

      // ✅ 拖拽结束
      window.addEventListener("mouseup", () => {
        isDragging = false;
        svg.style.cursor = "grab";
      });
    },
    // 4. 句子依存关系树
    async showSyntaxTree(sentence) {
      try {
        const response = await fetchSyntaxTree(sentence);
        const data = response.data;

        if (!data || !data.treeData) {
          console.warn("返回数据为空或格式不正确：", data);
          return;
        }

        // ✅ 更新 `sentenceDetails` 数据
        this.sentenceDetails = {
          sentence,
          type: data.sentenceType || "未分类",
          structure: data.treeData,
          suggestion: "根据语法结构建议优化表达。"
        };

        // ✅ 等待 DOM 渲染完成并对话框打开后再渲染内容
        this.$nextTick(() => {
          this.dialogVisible = true;

          // ✅ 确保对话框完全打开后再执行渲染
          this.$nextTick(() => {
            this.renderSyntaxTree();
            this.renderSyntaxStructure(sentence);
          });
        });
      } catch (error) {
        console.error("获取亮点句型详情失败:", error);
      }
    },

    // 5. 渲染依存句法树
    renderSyntaxTree() {
      const container = this.$refs.syntaxTree;

      if (!container) {
        console.warn("依存句法树容器未找到");
        return;
      }

      const chart = echarts.getInstanceByDom(container) || echarts.init(container);

      if (!this.sentenceDetails.structure) {
        console.warn("无有效的依存树数据");
        chart.clear();
        return;
      }

      const data = this.sentenceDetails.structure;

      const option = {
        series: [
          {
            type: 'tree',
            data: [data],
            top: '5%',
            left: '20%',
            bottom: '5%',
            right: '20%',
            symbol: 'circle',
            symbolSize: 10,
            label: {
              position: 'left',
              verticalAlign: 'middle',
              align: 'right',
              fontSize: 12
            },
            leaves: {
              label: {
                position: 'right',
                verticalAlign: 'middle',
                align: 'left'
              }
            },
            emphasis: {
              focus: 'descendant'
            },
            expandAndCollapse: true,
            animationDuration: 550,
            animationEasing: 'linear'
          }
        ]
      };

      chart.setOption(option);
    }
  },
  /**
   * 清空分析数据
   */
  clearAnalysisData() {
    console.log("清空分析数据");
    this.highlightSentences = [];
    this.sentenceDetails = {
      sentence: "",
      type: "",
      structure: null,
      suggestion: ""
    };

    // 清空图表
    const chartElement = this.$refs.syntaxChart;
    if (chartElement) {
      const chart = echarts.getInstanceByDom(chartElement);
      if (chart) {
        chart.clear();
      }
    }
  }
};
</script>



<style scoped>
.displacy-container {
  width: 100%;
  height: 200px;  /* 统一限制高度，防止超出 */
  background-color: transparent;  /* 背景透明 */
  overflow: hidden;  /* 防止超出容器 */
  display: flex;
  justify-content: center;
  align-items: center;
}
.displacy-container:active {
  cursor: grabbing;
}

.pa-4 {
  padding: 16px;
}
</style>
